import axios from "axios";
import store from "../store/index";
import { Message } from "element-ui";
import router from "./index";
// 用来拦截用的
axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
// 创建一个单例
const http = axios.create({
  baseURL: "https://dev.kizokulife.com/",
  timeout: 30000, // 响应时间
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

//拦截器  -请求拦截
http.interceptors.request.use(
  (config) => {
    //部分接口需要token
    let token = store.state.login.token || localStorage.getItem("token");
    store.commit('login/setUserinfo', { ...JSON.parse(localStorage.getItem('userInfo')) })
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
var flag = true
//拦截器  -响应拦截
http.interceptors.response.use(
  (res) => {
    if (res.data.code === 1) {
      return Promise.resolve(res.data);
    } else {
      Message({
        type: "error",
        message: res.data.msg
      });
      return Promise.reject(res.data);
    }
  },
  (err) => {
    if (err.response.status == 401) {
      if (flag) {
        Message({
          type: 'error',
          message: "登录后再操作"
        })
        flag = false
      }
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      router.push('/case')
    }
    console.log(err);
    return Promise.reject(err);
  }
);

//整体导出
export default http;
